package com.wangbo.rabbit;

import com.rabbitmq.client.Channel;
import com.wangbo.test.util.JacksonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MyMessageHandler implements ChannelAwareMessageListener {
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        // 邮递标签，消息在 Broker 中的唯一标识
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        // 消息来源队列名
        String queueName = message.getMessageProperties().getConsumerQueue();

        try {
            // 1. 接收转换消息
            RabbitMessage rabbitMessage = JacksonUtil.toBean(new String(message.getBody()).trim(), RabbitMessage.class);
            log.info("收到消息：messageId={}, payload={}", rabbitMessage.getMessageId(), rabbitMessage.getPayload());

            // 2. 处理业务逻辑

            // 3. 手动签收
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            e.printStackTrace();
            // 4. 拒绝签收策略
            // 第三个参数： requeue: 是否重回队列，如果设置为true，则消息重新回到queue, 消费端会重新消费
            channel.basicNack(deliveryTag, true, false);
        }
    }
}
